package com.gitee.huanminabc.dynamicdb.data;


import com.gitee.huanminabc.dynamicdb.config.DynamicDbSpringConfig;
import com.gitee.huanminabc.dynamicdb.core.DBSwatchUtil;
import com.gitee.huanminabc.dynamicdb.core.DynamicDataSourceContext;
import com.gitee.huanminabc.dynamicdb.dal.dao.DatasourceManager;
import com.gitee.huanminabc.dynamicdb.entity.DataSourceEneity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.DependsOn;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
* @Description: 从数据库中查询出全部的数据源,添加到数据源容器中* 优先级大于配置文件
* 表结构初始化文件: resources/sql/init.sql
* @Author: huanmin
* @Date: 2024/12/13
*/

//依赖于DynamicDataSourceConfig中的abstractRoutingDataSource
@DependsOn("abstractRoutingDataSource")
@Slf4j
public class DataSourceInitialize implements ApplicationRunner  {
    @Autowired(required = false)
    private DatasourceManager datasourceManager;
    @Autowired
    private DynamicDbSpringConfig dynamicDbSpringConfig;

    //项目启动后执行初始化数据源
    @Override
    public void run(ApplicationArguments args)  {

        if (dynamicDbSpringConfig.isDatabaseLoadActivate()){
            log.info("-----------------DataSourceInitialize------------------");
            try {

                DBSwatchUtil.toggleDB(dynamicDbSpringConfig.getDatabaseLoadKey(),()->{
                    log.debug("-----------------YmlDataSourceInitialize------------------");
                    Map<String,DataSourceProperties> multiDb = new HashMap<>();
                    List<DataSourceEneity> dataSources = datasourceManager.getDataSources();
                    for (DataSourceEneity dataSource : dataSources) {

                        DataSourceProperties dataSourceProperties = DynamicDataSourceContext.buildMultiDbDataSource(dataSource);
                        multiDb.put(dataSource.getKey(),dataSourceProperties);
                    }
                    DynamicDataSourceContext.addDataSource(multiDb);
                    return null;
                });
            } catch (Throwable e) {
                log.error("[DataSourceInitialize->run] 初始化数据源失败",e);
                System.exit(1);
            }
        }
    }
}
